import View, { connect, loadPackage, component } from "../utils/ui";


interface ILoading {
    sourceList?: string[],
    packageList?: string[]
}
@connect('Basic/Loading')
export class Loading extends View {
    progress: number;
    @component
    progressBar: fgui.GProgressBar
    totalCount: number = 0;
    _curCount: number = 0

    download(loadOpts: ILoading) {
        const promisies = [];
        const { packageList, sourceList } = loadOpts;
        if (sourceList && sourceList.length) {
            promisies.push(this.loadSource(sourceList))
        }
        if (packageList && packageList.length) {
            promisies.push(
                ...this.loadPackage(packageList)
            )
        }
        return Promise.all(promisies)
    }

    get curCount() {
        return this._curCount
    }
    set curCount(v) {
        this._curCount = v;
        this.updateProgress()
    }
    // 加载其他普通资源
    loadSource(sourceList: string[]) {
        let sourceLen = sourceList.length
        this.totalCount += sourceLen;
        let last = 0;
        const handleProgress = (progress) => {
            let downCount = sourceLen * progress;
            this.curCount += (downCount - last)
            last = downCount;
        }
        return new Promise((resolve, _reject) => {
            Laya.loader.create(sourceList,
                Laya.Handler.create(this, resolve),
                Laya.Handler.create(this, handleProgress),
            )
        })
    }
    // 加载fgui包
    loadPackage(packageNames: string[]) {
        this.totalCount += packageNames.length;
        return packageNames.map((packageName) => {
            return new Promise<void>((resolve, _reject) => {
                loadPackage(packageName, () => {
                    this.curCount += 1
                    resolve()
                })
            })
        })
    }

    updateProgress() {
        if (!this.progressBar) return;
        let progress = Number((this._curCount / this.totalCount).toFixed(2));

        this.progressBar.value = progress * 100
    }
}